package com.ygp.lock.rlock.threadsinal;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

/**
 * <Description> <br>
 *
 * @author linmiaolai@sanyygp.com<br>
 * @version 1.0<br>
 * @date 2021/11/19 <br>
 */
@Slf4j(topic = "c.BoundedContainer1")
public class BoundedContainer1 {
    private int count;

    private int putIndex;

    private int takeIndex;

    private Object[] items;

    private int cap;

    public BoundedContainer1(int initialCapacity) {
        this.cap = initialCapacity;
        this.count = 0;
        this.items = new Object[initialCapacity];
        this.putIndex = 0;
        this.takeIndex = 0;
    }


    public void put(Object item) {
        if (count == cap) {
            log.debug("满了，无法添加:{}", item);
            return;
        }
        if (putIndex == cap) {
            // 要重头开始
            putIndex = 0;
        }
        items[putIndex++] = item;
        count++;
    }

    public Object take() {
        if (count == 0) {
            log.debug("没有元素");
            return null;
        }
        if (takeIndex == cap) {
            takeIndex = 0;
        }
        Object item = items[takeIndex];
        items[takeIndex] = null;
        takeIndex++;
        count--;
        return item;
    }

    public void print() {
        System.out.println(Arrays.toString(items));
    }

    public static void main(String[] args) {
        BoundedContainer1 container = new BoundedContainer1(5);
        container.put(1);
        container.put(2);
        container.put(3);
        container.put(4);
        container.put(5);
        container.put(6);
        container.take();
        container.take();
        container.take();
        container.take();
        container.put(6);
        container.put(7);
        container.print();
    }
}
